package com.zensun.common.utils.sms;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.zensun.common.config.AliyunSmsProperties;
import com.zensun.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AliyunSmsUtil {

    private static AliyunSmsProperties aliyunSmsProperties = SpringUtils.getBean(AliyunSmsProperties.class);

    /**
     * 发送方法
     *
     * @param phone         电话号码
     * @param templateCode  模板编号
     * @param templateParam 模板中的参数
     * @return 返回值
     * @throws ClientException 异常
     */
    public static Boolean sendSms(String phone, String templateCode, String templateParam) {
        Boolean flag = false;

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile(aliyunSmsProperties.getRegionId(), aliyunSmsProperties.getAccessKeyId(), aliyunSmsProperties.getAccessKeySecret());
        SendSmsResponse sendSmsResponse = null;

        try {
            DefaultProfile.addEndpoint(aliyunSmsProperties.getRegionId(), aliyunSmsProperties.getRegionId(), aliyunSmsProperties.getProduct(), aliyunSmsProperties.getDomain());
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(phone);
            request.setSignName(aliyunSmsProperties.getSignName()); // 短信签名
            request.setTemplateCode(templateCode);
            request.setTemplateParam(templateParam);
            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            request.setOutId("10000");
            //hint 此处可能会抛出异常，注意catch
            sendSmsResponse = acsClient.getAcsResponse(request);
            if (sendSmsResponse.getCode().equals("OK")) {
                flag = true;
                log.info("给{}短信发送成功------", phone);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("给{}短信发送失败------", phone);
        }

        return flag;
    }

    /**
     * 生成六位随机数
     *
     * @return
     */
    public static String createRandomVcode() {
        //验证码
        StringBuilder vcode = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            vcode.append((int) (Math.random() * 9));
        }
        return vcode.toString();
    }
}
